package com.example.springtrans.controller;

import com.example.springtrans.service.UserService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;

@RequestMapping("/user")
@RestController
public class UserController {
    //JDBC事务管理器
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Autowired
    private UserService userService;

    @RequestMapping("/register")
    public boolean register(String userName,String password){
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);
        if(!StringUtils.hasLength(userName)||!StringUtils.hasLength(password)){
            return false;
        }
       Integer result = userService.insert(userName,password);
        //提交事务
        dataSourceTransactionManager.commit(transaction);
        //会滚事务
        dataSourceTransactionManager.rollback(transaction);
        return true;
    }
}
